package Base64知识点;

import java.io.*;
import java.util.Base64;

public class Base64ToImage {

    /**
     * 从文本文件中读取 Base64，并保存为图片
     * @param base64FilePath 存储 Base64 的 .txt 文件路径
     * @param outputImagePath 输出图片路径
     * @throws IOException
     */
    public static void convertBase64FileToImage(String base64FilePath, String outputImagePath) throws IOException {
        // 读取 Base64 内容
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(base64FilePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }

        // 解码并写出图片
        byte[] imageBytes = Base64.getDecoder().decode(sb.toString());
        try (OutputStream os = new FileOutputStream(outputImagePath)) {
            os.write(imageBytes);
        }
    }

    public static void main(String[] args) throws IOException {
        String base64File = "Base64ToImage.txt";
        String outputPath = "restored.jpg";
        convertBase64FileToImage(base64File, outputPath);
        System.out.println("图片还原成功！");
    }
}
